package com.ruoyi.filler.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.consumer.domain.FUser;
import com.ruoyi.consumer.domain.WxConfig;
import com.ruoyi.consumer.service.impl.FUserServiceImpl;
import com.ruoyi.consumer.utils.pay.HttpClient;
import com.ruoyi.consumer.utils.pay.HttpRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "加注员用户")
@RestController
@RequestMapping("/api/fUser")
public class FUsersController {
    @Autowired
    private FUserServiceImpl fUserService;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private RedisCache redisCache;

    @ApiOperation("根据code获取openid")
    @GetMapping("/getMyOpenid")
    public AjaxResult getMyOpenid(@ApiParam(value = "wx.login返回的code", required = true) String code) {
        String grant_type = "authorization_code";
        String params = "appid=" + wxConfig.getF_appid() + "&secret=" + wxConfig.getF_appSecret() + "&js_code=" + code + "&grant_type=" + grant_type;
        String sr = HttpRequest.sendPost("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject json = JSONObject.parseObject(sr);
        System.out.println("解析code请求结果:" + json.toString());
        String openid = json.getString("openid");
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("openid", openid);
        return ajaxResult;
    }

    @ApiOperation("解密code获取手机号")
    @GetMapping("/getMyPhone")
    public AjaxResult getMyPhone(@ApiParam(value = "此处是button获取的code，而不是wx.login的", required = true) String code) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + redisCache.getCacheObject("token:" + "findFillerAccessToken");
        System.out.println("access_token" + url);
        // 请求参数
        Map<String, String> map = new HashMap<>(1);
        map.put("code", code);

        // 发起请求 注意请求参数map要转成json字符串
        String res = HttpClient.postJson(url, JSON.toJSONString(map), null);

        // 解析请求结果 拿到手机号
        JSONObject jsonObject = JSONObject.parseObject(res);
        String phone_info = jsonObject.get("phone_info").toString();
        JSONObject jsonPhone_info = JSONObject.parseObject(phone_info);
        String phoneNumber = jsonPhone_info.get("phoneNumber").toString();

        System.out.println("用户手机号：" + phoneNumber);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("phoneNumber", phoneNumber);
        return ajaxResult;
    }

    @ApiOperation("注册新用户")
    @GetMapping("/loginNewUser")
    public AjaxResult loginNewUser(@ApiParam(value = "openid", required = true) String userOpenid,
                                   @ApiParam(value = "用户头像", required = true) String userHead,
                                   @ApiParam(value = "用户昵称", required = true) String userNick,
                                   @ApiParam(value = "用户手机号", required = true) String userPhone) {
        AjaxResult ajaxResult = new AjaxResult();
        FUser users = new FUser();
        users.setOpenid(userOpenid);
        //判断用户是否已经注册过
        List<FUser> usersList = fUserService.selectFUserList(users);
        if (usersList.size() > 0) {
            return ajaxResult.put("msg", "该用户已注册过，请勿重复注册");
        }
        FUser user = new FUser();
        user.setOpenid(userOpenid);
        user.setUserHeader(userHead);
        user.setUserNick(userNick);
        user.setUserPhone(userPhone);
        fUserService.insertFUser(user);
        ajaxResult.put("msg", "注册成功");
        ajaxResult.put("data", user);
        return ajaxResult;
    }

    @ApiOperation("根据openid判断用户注册")
    @GetMapping("/login")
    public AjaxResult login(@ApiParam(value = "openid", required = true) String userOpenid) {
        AjaxResult ajaxResult = new AjaxResult();
        FUser users = new FUser();
        users.setOpenid(userOpenid);
        List<FUser> usersList = fUserService.selectFUserList(users);
        if (usersList.size() > 0) {
            ajaxResult.put("msg", "该用户已存在");
            ajaxResult.put("data", usersList.get(0));
        } else {
            ajaxResult.put("msg", "该用户没有注册过");
        }
        return ajaxResult;
    }

    @ApiOperation("通过userid修改用户昵称头像")
    @GetMapping("/updataUserByUserId")
    public AjaxResult updataUserByUserId(@ApiParam(value = "userId", required = true) Integer userId,
                                         @ApiParam(value = "userNick", required = true) String userNick,
                                         @ApiParam(value = "UserName", required = true) String UserName,
                                         @ApiParam(value = "userHead", required = true) String userHead) {
        AjaxResult ajaxResult = new AjaxResult();
        FUser users = fUserService.selectFUserByUserId(userId);
        users.setUserHeader(userHead);
        users.setUserNick(userNick);
        users.setUserName(UserName);
        int i = fUserService.updateFUser(users);
        if (i > 0) {
            FUser users1 = fUserService.selectFUserByUserId(userId);
            ajaxResult.put("msg", "修改成功");
            ajaxResult.put("data", users1);
        } else {
            ajaxResult.put("msg", "服务器错误");
        }
        return ajaxResult;
    }
}
